<template>
    <div style="padding: 10px 15px" class="img-upload-container">
            <el-upload
                :action="imgLoadPath"
                :show-file-list="false"
                :on-error="handleError"
                :on-success="handleBeforeUpload1"
                :before-upload="beforeUpload"
            >
                <div class="zhenjian-id-box" style="border: 1px dashed #eee">
                    <el-image style="width: 150px; height: 150px" :src="requestFilter(imgModelUrl)" fit="fill" v-if="imgModelUrl"></el-image>
                    <div class="zhenjian-id-box zhenjian-flex" v-else>请上传图片</div>
                </div>
            </el-upload>
        </div>
</template>

<script>
export default {
    name: 'IDReady',
    props: ['imgUrl'],
    data() { 
        return {
            imgModelUrl: '',
            docLoadPath: '',
            imgLoadPath: this.$API.LOGIN_IMG,
            uploadLogin: null
        };
    },
    watch: {
        imgUrl: function (val, oldVal) {
            if (val != oldVal) {
                this.imgModelUrl = val;
            }
        }
    },
    created() {
        if (this.imgUrl) {
            this.imgModelUrl = this.imgUrl;
        }
    },
    methods: {
        requestFilter(val){
            if(val){
                if(val.indexOf('http') === -1){
                    return this.$API.ASSET_IMAGES_URL+val
                }else{
                    return val
                }
            }
            return '';
        },
        //身份证正面上传成功
        handleBeforeUpload1(response) {
            this.uploadLogin.close();
            if (response.code == 1) {
                console.log('response',response);
                this.imgModelUrl = response.data;
                this.$emit('update:imgUrl', response.data);
                this.$message.success('上传成功');
            } else {
                this.$message.error(response.msg);
            }
        },
        beforeUpload: function (file) {
            var FileExt = file.name.replace(/.+\./, '');
            if (['jpg', 'jpeg', 'png'].indexOf(FileExt.toLowerCase()) === -1) {
                this.$message({
                    type: 'warning',
                    message: '请上传jpg,jpeg,png格式文件！'
                });
                return false;
            }
            this.uploadLogin = this.$loading({ text: '加载中...' });
        },
        handleError(){
            this.uploadLogin.close();
            this.$message.error('上传失败');
        },
    }
};
</script>

<style scoped>
.zhenjian-id-box {
    width: 150px;
    height: 150px;
    font-size: 14px;
    color: #888;
    text-align: center;
    line-height: 150px;
    border-radius: 4px;
}
</style>
